package xluz.droidacts.sanLiuJiu;

import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;

/*
  Game high scores records

Copyright (c) 2015 Cecil Cheung
This software is released under the GNU General Public License version 3.
See, for example, "http://www.gnu.org/licenses/gpl.html".
*/


public class HiScoresKeeper {
	static final String STATUS_SCORES = "HiScores";
	android.content.Context mainApp;
	int[] scores1, scores2, gamMode, gamDate;
	StringBuffer[] P1names; 

	public HiScoresKeeper(Context appContx) {
		gamDate = new int[BestMove.MAX_AI_Level * 2];
		gamMode = new int[BestMove.MAX_AI_Level * 2];
		scores1 = new int[BestMove.MAX_AI_Level * 2];
		scores2 = new int[BestMove.MAX_AI_Level * 2];
		P1names = new StringBuffer[BestMove.MAX_AI_Level * 2];
		for(int i=0; i < BestMove.MAX_AI_Level * 2; i++) {
			P1names[i] = new StringBuffer();
		}
		mainApp = appContx;
		loadScores();
	}

	public void saveScores() {
		SharedPreferences savedScor = mainApp.getSharedPreferences(STATUS_SCORES, Activity.MODE_PRIVATE);
		SharedPreferences.Editor outxml = savedScor.edit();

		for(int i=1; i<= BestMove.MAX_AI_Level * 2; i++) {
			outxml.putString("Pname_"+Integer.toString(i), P1names[i-1].toString());
			outxml.putInt("gameMode_"+Integer.toString(i), gamMode[i-1]);
			outxml.putInt("gameDate_"+Integer.toString(i), gamDate[i-1]);
			outxml.putInt("score1_"+Integer.toString(i), scores1[i-1]);
			outxml.putInt("score2_"+Integer.toString(i), scores2[i-1]);
		}
		outxml.apply();
	}

	public void loadScores() {
		SharedPreferences savedScor = mainApp.getSharedPreferences(STATUS_SCORES, Activity.MODE_PRIVATE);
		for(int i=1; i<= BestMove.MAX_AI_Level * 2; i++) {
			gamDate[i-1] = savedScor.getInt("gameDate"+"_"+Integer.toString(i), 0);
			gamMode[i-1] = savedScor.getInt("gameMode"+"_"+Integer.toString(i), 0);
			scores1[i-1] = savedScor.getInt("score1"+"_"+Integer.toString(i), 0);
			scores2[i-1] = savedScor.getInt("score2"+"_"+Integer.toString(i), 0);
			P1names[i-1].append(savedScor.getString("Pname_"+Integer.toString(i),"P 1"));
		}

	}

	public int recordScores(int gMode, int gDate, int score1, int score2, String Pname) {
		if((gMode/64)%2 == 1) return -1;
		int j = gMode % 16;
		// sanity checks for game level
		if(j < 1) j = 1;
		if(j > BestMove.MAX_AI_Level) j = BestMove.MAX_AI_Level;
		if((gMode/32)%2 == 1) j += BestMove.MAX_AI_Level;
		j--;
		if(score1 > this.scores1[j]) {
			P1names[j].replace(0, P1names[j].length(), Pname);
			gamDate[j] = gDate;
			gamMode[j] = gMode;
			scores1[j] = score1;
			scores2[j] = score2;
			return j+1;
		}
		return 0;
	}

}
